package rssmanager.service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * @author Hanumant Shikhare
 */
public class Reader {
	private URL url;
	private XmlReader reader;
	private SyndFeed feed;
	private SyndEntry entry;
	private boolean flag_read=false;
	private boolean flag_valid_url=false;
	private ArrayList<String> entries_titles_list,  entries_descs_list, entries_dates_list, entries_uris_list;
	private String feed_title;

	public Reader(String url) throws IllegalArgumentException, IOException, FeedException {
		try {
			this.url  = new URL(url);
			flag_valid_url=true;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			flag_valid_url=false;
			e.printStackTrace();
		}
		reader = null;
		read();
	}
	private void read() throws IOException, IllegalArgumentException, FeedException {

		try {
			reader = new XmlReader(url);
			feed = new SyndFeedInput().build(reader);
			feed_title = new String();
			entries_titles_list = new ArrayList<String>();
			entries_descs_list = new ArrayList<String>();
			entries_dates_list = new ArrayList<String>();
			entries_uris_list = new ArrayList<String>();
			feed_title = feed.getTitle();
			for (Iterator i = feed.getEntries().iterator(); i.hasNext();) {
				entry = (SyndEntry) i.next();
				entries_titles_list.add(entry.getTitle());
				entries_descs_list.add(entry.getDescription().getValue());
				entries_dates_list.add(entry.getPublishedDate().toGMTString());
				entries_uris_list.add(entry.getUri());
			}
			flag_read = true;		
			if (reader != null)
					reader.close();
		} catch(NullPointerException e) {
			flag_read = false;
			e.printStackTrace();
		}
	}

	public ArrayList<String> getDecsList() {
		return entries_descs_list;
	}

	public ArrayList<String> getDatesList() {
		return entries_dates_list;
	}

	public ArrayList<String> getUrisList() {
		return entries_uris_list;
	}

	public ArrayList<String> getTitlesList() {
		return entries_titles_list;
	}

	public boolean getReadFlag() {
		return flag_read;
	}
	
	public boolean getValidURLFlag() {
		return flag_valid_url;
	}
}